package org.springblade.modules.enterprise.controller;

import com.baidu.ueditor.ActionEnter;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.modules.resource.endpoint.LocalEndpoint;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("esms/ueditor")
@Api(value = "UEditor所需接口", tags = "UEditor所需接口")
public class UEditorController {

	LocalEndpoint localEndpoint;

	public static JSONObject jsonConfig;

	@RequestMapping("/config")
	public String config(HttpServletRequest request, MultipartFile upfile) {
		final String action = request.getParameter("action");
		if (action.equals("uploadimage")) {
			final R<Map<String, Object>> result = localEndpoint.arrayFileUpload(upfile);
			final Map<String, Object> data = result.getData();
			data.put("state","SUCCESS");
			return JsonUtil.toJson(data);
		} else {
			if (jsonConfig == null){
				String result = "";
				try {
					result = IOUtils.toString(this.getClass().getResourceAsStream("/config/ueditor/config.json")
						, StandardCharsets.UTF_8);
				} catch (IOException e) {
					return "配置文件初始化失败";
				}

				jsonConfig = new JSONObject(filter(result));
			}
			return jsonConfig.toString();
		}
	}

	private String filter(String input) {
		return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
	}
}
